layui.use(['table', 'admin', 'ax', 'func','treeTable'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    let treeTable = layui.treeTable;

    /**
     * 地区表管理
     */
    var Area = {
        tableId: "areaTable"
    };

    /**
     * 初始化表格的列
     */
    Area.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {type: 'numbers', title: '序号', width: 80},
            {field: 'id', hide: true, sort: true, title: 'id'},
            {field: 'name', sort: true, title: '简名', edit: 'text'},
            {field: 'fullName', sort: true, title: '全名', edit: 'text'},
            /*{field: 'pinYin', sort: true, title: '拼音'},
            {field: 'location', sort: true, title: '位置'},
            {field: 'cIdx', sort: true, title: ''},
            {field: 'parentId', sort: true, title: '上级id'},
            {field: 'createUser', sort: true, title: '创建人'},
            {field: 'createTime', sort: true, title: '创建时间'},
             {field: 'updateUser', sort: true, title: '修改人'},
            {field: 'updateTime', sort: true, title: '修改时间'},
            {field: 'deleteFlag', sort: true, title: '删除标记 0:正常 1:删除'},*/
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    Area.search = function () {
        var queryData = getParam();

        table.reload(Area.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 获取查询参数
     */
    function getParam() {
        var queryData = {};
        queryData['name'] = $('#name').val();
        return queryData;
    }

    /**
     * 跳转到添加页面
     */
    Area.jumpAddPage = function () {
        window.location.href = Changein.ctxPath + '/area/add'
    };

    /**
     * 跳转到编辑页面
     *
     * @param data 点击按钮时候的行数据
     */
    Area.jumpEditPage = function (data) {
        window.location.href = Changein.ctxPath + '/area/edit?id=' + data.id
    };

    /**
     * 删除
     */
    var deleteBatchLock = false;
    Area.deleteBatch = function () {
        if (!deleteBatchLock) {
            var checkRows = table.checkStatus(Sample.tableId);
            if (checkRows.data.length == 0) {
                Changein.error("请选择要删除的数据");
                return false;
            }
            var arr = [];
            var tabData = checkRows.data;
            for (var i = 0; i < tabData.length; i++) {
                if (tabData[i].audit != 1) {
                    arr.push(tabData[i].id);
                }
            }
            if (arr.length == 0) {
                Changein.error("选中数据全部已审核，请选择未审核的数据");
                return false;
            }
            var operation = function () {
                deleteBatchLock = true;
                var ajax = new $ax(Changein.ctxPath + "/area/batchDeleteByIds", function (data) {
                    if (data.code != 200) {
                        Changein.error("删除失败！" + data.message);
                    } else {
                        Changein.success("删除成功！");
                    }
                    deleteBatchLock = false;
                    table.reload(Area.tableId);
                }, function (data) {
                    deleteBatchLock = false;
                    Changein.error("删除失败！" + data.responseJSON.message)
                });
                ajax.set({"ids": arr.toString()});
                ajax.start();
            }
            Changein.confirm("是否删除?", operation);
        } else {
            Changein.error("正在删除中");
        }
    };

    /**
     * 审核
     */
    var auditLock = false;
    Area.auditBatch = function () {
        if (!auditLock) {
            var arr = [];
            var checkRows = table.checkStatus(Area.tableId);
            if (checkRows.data.length == 0) {
                Changein.error("请选择要审核的数据");
                return false;
            }
            var tabData = checkRows.data;
            for (var i = 0; i < tabData.length; i++) {
                if (tabData[i].audit != 1) {
                    arr.push(tabData[i].id);
                }
            }
            if (arr.length == 0) {
                Changein.error("选中数据全部已审核");
                return false;
            }
            var operation = function () {
                auditLock = true;
                var ajax = new $ax(Changein.ctxPath + "/area/setAudit", function (data) {
                    if (data.code != 200) {
                        Changein.error("审核失败！" + data.message);
                    } else {
                        Changein.success("审核成功！");
                    }
                    auditLock = false;
                    table.reload(Area.tableId);
                }, function (data) {
                    auditLock = false;
                    Changein.error("审核失败！" + data.responseJSON.message)
                });
                ajax.set({"id": arr.toString()});
                ajax.start();
            }
            Changein.confirm("是否审核?", operation);
        } else {
            Changein.error("正在审核中");
        }
    };

    /**
     * 反审核
     */
    var unAuditLock = false;
    Area.unAuditBatch = function () {
        if (!unAuditLock) {
            var arr = [];
            var checkRows = table.checkStatus(Area.tableId);
            if (checkRows.data.length == 0) {
                Changein.error("请选择要反审核的数据");
                return false;
            }
            var tabData = checkRows.data;
            for (var i = 0; i < tabData.length; i++) {
                if (tabData[i].audit == 1) {
                    arr.push(tabData[i].id);
                }
            }
            if (arr.length == 0) {
                Changein.error("选中数据全部未审核");
                return false;
            }
            var operation = function () {
                unAuditLock = true;
                var ajax = new $ax(Changein.ctxPath + "/area/setUnAudit", function (data) {
                    if (data.code != 200) {
                        Changein.error("反审核失败！" + data.message);
                    } else {
                        Changein.success("反审核成功！");
                    }
                    unAuditLock = false;
                    table.reload(Area.tableId);
                }, function (data) {
                    unAuditLock = false;
                    Changein.error("反审核失败！" + data.responseJSON.message)
                });
                ajax.set({"id": arr.toString()});
                ajax.start();
            }
            Changein.confirm("是否反审核?", operation);
        } else {
            Changein.error("正在反审核中");
        }
    };


    /**
     * 导出excel按钮,EXPORT_CODE需要在开发设置-导出设置里配置
     */
    Area.exportExcel = function () {
        Changein.exportData(tableResult.config.id, "EXPORT_CODE", table, getParam());
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    Area.onDeleteItem = function (data) {
        var operation = function () {
            debugger
            var ajax = new $ax(Changein.ctxPath + "/area/editItem", function (data) {
                Changein.success("删除成功!");
                initTable.refresh(Area.tableId);
            }, function (data) {
                Changein.error("删除失败!" + data.responseJSON.message + "!");
            });
            let dataParam = {id: data.id};
            dataParam.deleteFlag = 1;
            ajax.set(dataParam);
            ajax.start();
        };
        Changein.confirm("是否删除?", operation);
    };
    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    var deleteLock = false;
    Area.onDeleteItem = function (data) {
        if (data.audit == 1) {
            Changein.error("选中数据已审核，请选择未审核的数据");
            return false;
        }
        var operation = function () {
            deleteLock = true;
            var ajax = new $ax(Changein.ctxPath + "/area/editItem", function (data) {
                deleteLock = false;
                if (data.code != 200) {
                    Changein.error("删除失败！" + data.message);
                } else {
                    Changein.success("删除成功！");
                }
                initTable.refresh(Area.tableId);
            }, function (data) {
                deleteLock = false;
                Changein.error("删除失败!" + data.responseJSON.message + "!");
            });

            let dataParam = {id: data.id};
            dataParam.deleteFlag = 1;
            ajax.set(dataParam);
            ajax.start();
        };
        if (!deleteLock) {
            Changein.confirm("是否删除?", operation);
        } else {
            Changein.error("正在删除中");
        }
    };

    // 渲染表格
   /* var tableResult = table.render({
        elem: '#' + Area.tableId,
        url: Changein.ctxPath + '/area/list',
        page: true,
        height: "full-130",
        cellMinWidth: 100,
        limit: 20,
        limits: [20, 30, 50, 100],
        cols: Area.initColumn()
    });*/

    //初始表格数据
    Area.initTable = function (areaId, data) {
        return treeTable.render({
            id: areaId,
            elem: '#' + areaId,
            url: Changein.ctxPath + '/area/listTree',
            where: data,
            page: false,
            height: "full-130",
            cellMinWidth: 100,
            tree: {
                iconIndex: 3,           // 折叠图标显示在第几列
                accordion: true,
                showLine: true,
                isPidData: true,
                idName: 'id',
                pidName: 'parentId'
            },
            cols: Area.initColumn()
        });
    };



    let initTable = Area.initTable(Area.tableId);
    //展开所有

    $("body").on("click", "[id='expandAll']", function () {
        initTable.expandAll();  // 展开全部
    })
    //折叠所有
    $("body").on("click", "[id='foldAll']", function () {
        initTable.foldAll();  // 折叠全部
    })

    // 搜索按钮点击事件
    $("body").on("click", "[id='btnSearch']", function () {
        let val = $('#name').val().trim();
        if (!val) {
            initTable.clearFilter();   // 清除搜索
            return;
        }
        initTable.filterData(val);  // 搜索
    })

    //监听表格
    treeTable.on('edit(areaTable)', function(obj){
        let id = obj.data.id;
        if (!obj.value) return;
        let formData = new FormData();
        let field = obj.field;
        formData.append("id",id);
        formData.append(field,obj.value);
        $.ajax({
            url: Changein.ctxPath + "/area/editItem",
            type: 'POST',
            data: formData,
            dataType: 'JSON',
            cache: false,
            processData: false,
            contentType: false,
            success: function (data) {
                Changein.success("修改成功！");
                if (field == 'name') {
                    initTable.refresh();  // 刷新(异步模式)
                }
            }
        });

    });
    /**
     * 弹出添加对话框
     */
    Area.openAddDlg = function () {
        func.open({
            title: '添加区域',
            maxmin:true,
            btn:["关闭"],
            content: Changein.ctxPath + '/area/add',
            tableId: Area.tableId
        });
    };
    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        Area.openAddDlg();
    });
    // 删除
    $("#btnDel").click(function () {
        Area.deleteBatch();
    });

    //审核
    $('#btnAudit').click(function () {
        Area.auditBatch();
    });

    //反审核
    $('#btnUnAudit').click(function () {
        Area.unAuditBatch();
    });
    // 导出excel
    $('#btnExp').click(function () {
        var checkRows = table.checkStatus(Area.tableId);
        if (checkRows.data.length === 0) {
            Area.exportExcel();
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    });
    //下载模板,TEMPLATE_CODE需要在开发设置-模板管理里配置
    $("#btnDownloadTemplate").click(function () {
        Changein.downLoadTempate("TEMPLATE_CODE");
    });
    // 工具条点击事件
    treeTable.on('tool(' + Area.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Area.jumpEditPage(data);
        } else if (layEvent === 'delete') {
            Area.onDeleteItem(data);
        }
    });
});
